package com.jinbai.servlet.track;

import com.jinbai.repo.TrackRepo;
import com.jinbai.util.Log;
import com.jinbai.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/studio/track/upload.do")
@MultipartConfig
public class UploadDoServlet extends HttpServlet {
    private final TrackRepo trackRepo = new TrackRepo();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserVO userVO = null;
        // 验证用户是否登录，如果没有登录跳转至登录页面
        final HttpSession session = req.getSession(false);
        if (session != null) {
            userVO = (UserVO) session.getAttribute("currentUser");
        }
        if (userVO == null) {
            // 代表用户没有登录
            Log.println("用户未登录");
            resp.sendRedirect("/studio/user/login.html");
            return;
        }

        Log.println("登录用户成功： " + userVO);
        // 登录成功
        // 从请求中获取需要的信息
        req.setCharacterEncoding("utf-8");
        final String title = req.getParameter("title");
        Log.println("获取到的title是： " + title);

        final Part track = req.getPart("track");
        final String contentType = track.getContentType(); // 从请求中得到数据类型
        Log.println("获取到的类型是：" + contentType);

        final InputStream inputStream = track.getInputStream(); // 从请求中获取数据内容
        trackRepo.insert(userVO.getUid(), title, contentType, inputStream);
        Log.println("上传成功");
        resp.sendRedirect("/studio/track/list.html");
    }
}
